import Xlsx from "xlsx";
import fs from "file-saver";

const s2ab = (s) => {
  var buf;
  if (typeof ArrayBuffer !== "undefined") {
    buf = new ArrayBuffer(s.length);
    var view = new Uint8Array(buf);
    for (var i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xff;
    return buf;
  } else {
    buf = new Array(s.length);
    for (var i = 0; i != s.length; ++i) buf[i] = s.charCodeAt(i) & 0xff;
    return buf;
  }
};

export function excelExport(table, filename) {
  const wb = Xlsx.utils.table_to_book(table);

  const defaultCellStyle = {
    font: { name: "Verdana", sz: 13, color: "FF00FF88" },
    fill: { fgColor: { rgb: "FFFFAA00" } },
  };

  const wopts = {
    bookType: "xlsx",
    bookSST: false,
    type: "binary",
    cellStyle: true,
    defaultCellStyle: defaultCellStyle,
    showGridLines: false,
  };

  const wbout = Xlsx.write(wb, wopts);
  const blob = new Blob([s2ab(wbout)], { type: "spplication/octet-stream" });
  fs.saveAs(blob, filename + ".xlsx");
}

export function excelInport(file, output) {
  const reader = new FileReader();
  reader.readAsArrayBuffer(file, "utf-8");
  reader.onloadend = function (e) {
    const data = e.target.result;
    console.log("data", data);
    const wb = Xlsx.read(data, {
      type: "buffer",
    });
    const ws = wb.Sheets[wb.SheetNames[0]];
    console.log("ws", ws);
    output.innerHTML = Xlsx.utils.sheet_to_html(ws);
  };
}
